package com.itheima.health.controller;

import com.aliyuncs.http.HttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.health.common.BaseContext;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.User;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author ：贝
 * @date ：Created in 2022年06月07日
 * @description ：
 * @version: 1.0
 */
@RequestMapping("/mobile/login")
@RestController
@Slf4j
public class LoginController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private MemberService memberService;

    @PostMapping("/smsLogin")
    public Result login(@RequestBody Map map, HttpServletRequest request){
        String telephone = map.get("telephone").toString();
        String validateCode = map.get("validateCode").toString();
        String redisKey = RedisConstant.VALIDATE_CODE_PREFIX +"_MOBILE_SIGNIN_"+telephone;
        //从redis里获取验证码
        String code = redisTemplate.opsForValue().get(redisKey).toString();

        //对验证码进行判断
        if (validateCode.equals(code)){
            //存到线程里
            BaseContext.setCurrentId(Long.parseLong(telephone));

            redisTemplate.delete(telephone);
              //创建会员对象
            Member member = new Member();
            //把手机号存进去
            member.setPhoneNumber(telephone);
            //调用方法
             member = memberService.updateBytelephone(member);
            //存储到session
            request.getSession().setAttribute("member",member);

            return new Result(true, MessageConst.LOGIN_SUCCESS);
        }
        return new Result(false,MessageConst.LOGIN_FAIL);
    }
}
